<template>
    <div :id="mapId" style="height: 100%; width: 100%;" v-on:dblclick="dbClick()"></div>
</template>

<script>
  import * as HMAP from './hmap.manage.js'
  export default {
    props: {
      type: String,
      url: String,
      nameKey: String,
      nameKey1: String
    },
    data () {
      return {
        mapId: 'pointaddlist_' + Math.random().toString(36).substr(2),
        mapManager: null,
        floorId: ''
      }
    },
    activated() {
      if (this.mapManager) {
        this.mapManager.setMapWork(true)
      }
    },
    deactivated() {
      if (this.mapManager) {
        this.mapManager.setMapWork(false)
      }
    },
    beforeDestroy () {
      if (this.mapManager) {
        this.mapManager.destroy()
        this.mapManager = null
      }
    },
    computed: {
      floorList: {
        get () {
          return this.$store.state.shopdata.floorList
        }
      }
    },
    mounted() {
      this.mapManager = new HMAP.Hmap(this.mapId, {
      	mapStorage: true, 						      // 使用地图缓存功能，加快加载速度
      	viewMode: HMAP.ViewMode.Mode_3D, 	// 初始二维还是三维状态,默认是3D状态
        maxDistance: 2000000,               // 摄像头最远距离
      });
      this.mapManager.on('onMapClick', (e) => {
        var name = "";
        var intersects = e.intersects || []
        for(var i=0; i<intersects.length; i++) {
          if(intersects[i].object.type == "Mesh" && intersects[i].object.objId != 'mark1') {
            if(intersects[i].object.name != '') {
              name = intersects[i].object.name;
            } else if(intersects[i].object.parent && intersects[i].object.parent.name != '') {
              name = intersects[i].object.parent.name;
            }
            break;
          }
        }
        if(e.position) {
          this.setMarkPoint(this.floorId, e.position.x, e.position.y, e.position.z);
          this.$emit('onMapClick', {name: name, x: this.toFixed(e.position.x), y: this.toFixed(e.position.y), z: this.toFixed(e.position.z)});
        }
        if(e.object){
          this.$emit('onDataClick', {id: e.object.objId, name: e.object.text});
        }
      })
      this.mapManager.on('onParkList', (e) => {
      	this.$emit('onParkList', e);
      })
      this.mapManager.on('onBeaconList', (e) => {
      	this.$emit('onBeaconList', e);
      })
    },
    methods: {
      dbClick() {
        this.$emit("dbClick")
      },
      resize() {
        this.$nextTick(() => {
          if (this.mapManager) {
            this.mapManager.resize()
          }
        })
      },
      _getMapFile(floorData) {
        if(!floorData) {
          return null;
        }
        if(this.type === 'ibeacon') {
          return floorData.ibeaconMap
        } else if(this.type === 'vr') {
          return floorData.vrMap
        }
        return floorData.mapFile
      },
      _getFloorData(floorId) {
        for(var i=0; i<this.floorList.length; i++) {
          if(this.floorList[i].id === floorId) {
            return this.floorList[i];
          }
        }
        return null;
      },
      showFloor(floorId) {
        if(!this.mapManager) {
          return;
        }
        if( !floorId || floorId === "" ) {
          this.mapManager.showFloors([]);
          return;
        }
        this.floorId = floorId;
        var floorData = this._getFloorData(floorId);
        this.mapManager.addFloor({
        	floorId: floorId,  				// 必须：楼层Id
        	floorName: floorData.name,					// 必须：楼层名称
        	floorHeight: floorData.height,						// 必须: 楼层展示的z坐标
        	floorMap: this._getMapFile(floorData),							// 必须: 地图文件
        	buildingName: floorData.buildingName,					// 必须: 所属楼宇
        	longitude: floorData.longitude,
        	latitude: floorData.latitude
        })
        this.mapManager.showFloors([floorId]);
        this.mapManager.spreadMap({
        	spreadRatio: 1, 									// 伸缩倍数
        	duration: 0.3,											// 动画秒数
          rotateAngle: floorData.singleRotateAngle,	// 地图旋转角度
          tiltAngle: 90,										// 地图到xy面的角度
          distance: floorData.singleCameraDis,									// 摄像头距离中心点距离
        	targetX: floorData.centerX,									   		// 目标点X轴
        	targetY: floorData.centerY,									   		// 目标点Y轴
        	targetZ: 0									   		// 目标点Z轴
        })
        this.refreshList();
      },
      // findGroupName(item) {
      //   if(this.mapManager) {
      //     return this.mapManager.findGroupName(item.x, item.y, item.floor.id)
      //   }
      //   return ""
      // },
      setMarkPoint(floorId, x, y, z) {
        if(x == null || y == null || x == '' || y == '') {
          return;
        }
        this.mapManager.addMesh({
          objId: 'mark1',												// 必须：这个模型对应的ID,唯一
          objType: 'mark',									// 选填：类型区分 默认mesh
          floorIds: [floorId],    									// 必须：隶属于哪些楼层，如果只有一个，直接添加到该楼层，无/多个添加到scene, 无则不受控制，多个时跟随楼层状态展示
          meshUrl: 'point',											// 必须：模型的url
          canSelect: false,									// 选填: 是否可以被选中
          x: x,															// 必须：坐标x
          y: y,															// 必须：坐标y
          z: z,															// 必须：坐标z (本楼层或场景中坐标z)
        })
      },
      removeMarkPoint(objId) {
        this.mapManager.removeTextById(objId)
        this.mapManager.removeMeshById(objId)
      },
      addMarkPoint(id, name, floorId, x, y, z,flag, color ) {
        this.mapManager.addText({
          floorId: floorId,    							// 必须：楼层
          x: x,															// 必须：坐标x
          y: y,															// 必须：坐标y
          z: z,														  // 必须：坐标z (本楼层中的坐标z)
          text: name,												// 必须：文本内容
          objId: id,												// 必须：这个文本对应的ID,唯一
          objType: 'text',									// 选填：类型区分 默认text
          size: 12,													// 选填：展示大小 默认16
          color: color || "#333333", 								// 选填：字体的颜色
          canSelect: true,									// 选填：是否能被选中，为true时，onMapClick有数据返回
          crashCheck: false,								// 选填：是否参与碰撞检测，参与的对象之间会进行检测
          sizeAttenuation: false,   				  // 选填：控制图标是否随地图放缩变化，默认 false,就是保持一定大小
          depthTest: true, 									// 选填：开启深度测试设置为false后，不被任何物体遮挡
          flag: flag
        })
        this.mapManager.addMesh({
          objId: id,												// 必须：这个模型对应的ID,唯一
          objType: 'mesh',									// 选填：类型区分 默认mesh
          floorIds: [floorId],    									// 必须：隶属于哪些楼层，如果只有一个，直接添加到该楼层，无/多个添加到scene, 无则不受控制，多个时跟随楼层状态展示
          meshUrl: 'point',											// 必须：模型的url
          canSelect: false,									// 选填: 是否可以被选中
          angle: 0,													// 选填: 旋转角度，0～359
          x: x,															// 必须：坐标x
          y: y,															// 必须：坐标y
          z: z															// 必须：坐标z (本楼层或场景中坐标z)
        })
      },
      isException(name, exceptionList) {
          for(var i=0; i<exceptionList.length; i++) {
            if(exceptionList[i].name == name) {
              return true;
            }
          }
          return false;
      },
      // 获取数据列表
      refreshList () {
        if(!this.floorId || this.floorId === '') {
          return
        }
        if(!this.url || this.url === '') {
          return
        }
        var self = this;
        this.$http({
          url: this.url,
          method: 'get',
          params: {
            'pageNo': 1,
            'pageSize': 100000,
            'orderBy': '',
            'floor': {
              id: this.floorId
            }
          }
        }).then(({data}) => {
          if (data && data.success) {
            this.mapManager.removeMeshById('mark1')
            var flag = new Date().getTime();
            var dataList = data.page.list
            var exception = data.exception || [];

            dataList.forEach((item) => {
              var textData = this.mapManager.getTextById(item.id);
              if(textData) {
                textData.flag = flag
              } else {
                var name = item['name']
                if(!name || name == '') {
                  name = item[this.nameKey]
                  if(this.nameKey1 && item[this.nameKey1]) {
                    name += '~'+item[this.nameKey1]
                  }
                }
                if(this.isException(name, exception)) {
                    // console.log("异常："+item['name'])
                   this.addMarkPoint(item.id, name, this.floorId, item.x, item.y, item.z || 0, flag, "#ff0000");
                } else {
                   // console.log("无异常："+item['name'])
                   this.addMarkPoint(item.id, name, this.floorId, item.x, item.y, item.z || 0, flag);
                }
              }
            })
            var textMap = this.mapManager.getAllText();
            textMap.forEach(function(textData, objId) {
            	if(textData.flag != flag) {
            		self.removeMarkPoint(objId)
            	}
            })
          }
        })
      }
    }
  }
</script>
<style>
</style>
